//
//  YKEmotinoPageView.m
//  youkan
//
//  Created by 吴高烽 on 16/4/23.
//  Copyright © 2016年 Honsintech. All rights reserved.
//

#import "YKEmotinoPageView.h"
#import "YKEmotions.h"
#import "YKEmotionTabBarButton.h"
#import "YKEmotionPopView.h"
#import "YKEmotinoButton.h"
@interface  YKEmotinoPageView()
@property (nonatomic ,strong)YKEmotionPopView *popView;
@end
@implementation YKEmotinoPageView
-(YKEmotionPopView *)popView{
    if (!_popView) {
        _popView =[YKEmotionPopView popView];
    }
    return _popView ;
}
-(instancetype)initWithFrame:(CGRect)frame{
    if (self =[super initWithFrame:frame]) {
        [self setUpAllChilen];
    }
    return self;
}
-(void)setUpAllChilen{
    
}
-(void)layoutSubviews{
    [super layoutSubviews];
    NSUInteger count =self.emotions.count;
    CGFloat btnW =(self.width-16)/YKEmotionMaxCols;
    CGFloat btnH =(self.height-16)/YKEmotionMaxRows;
    for (int i=0; i<count; i++) {
        UIButton *btn =self.subviews[i];
        btn.x = 8 + btnW * (i%YKEmotionMaxCols);
        btn.y = 8 + btnH * (i/YKEmotionMaxCols);
        btn.width = btnW ;
        btn.height =btnH ;
    }
}
// CUICatalog: Invalid asset name supplied: (null)  图片源不存在
-(void)setEmotions:(NSArray *)emotions{
    _emotions = emotions;
    NSUInteger count =emotions.count;
    for (int i=0; i<count; i++) {
        YKEmotinoButton *btn =[[YKEmotinoButton alloc]init];
        [self addSubview:btn];
        btn.emotion = emotions[i];
        
//        NSString *imge =[NSString stringWithFormat:@"lxh/%@",emotion.png];
//        NSString *path =[[NSBundle mainBundle]pathForResource:imge ofType:nil];
//        UIImage *image =[UIImage imageWithContentsOfFile:path];

        [btn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
//        [btn setImage:[UIImage imageNamed:emotion.png] forState:UIControlStateNormal];
    }
}
-(void)btnClick:(YKEmotinoButton*)btn{
//    [self addSubview:self.popView];
    self.popView.emotion = btn.emotion;
    UIWindow *window =[[UIApplication sharedApplication].windows lastObject];
    [window addSubview:self.popView];
//!>    坐标轴转化，计算被点击按钮在Window中的frame
    CGRect btnFrame =[btn convertRect:btn.bounds toView:window];
    self.popView.y = CGRectGetMidY(btnFrame) - self.popView.height ;
    self.popView.centerX = CGRectGetMidX(btnFrame);
//  0.3秒后让预览的按钮自动消息
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self.popView removeFromSuperview];
    });
//!>    发通知
    NSMutableDictionary *userInfo =[NSMutableDictionary dictionary];
    userInfo[YKEmotionSelect]=btn.emotion;
    [YKNotificationCenter postNotificationName:YKEmotionSelectedtNotification object:nil userInfo:userInfo];
}
@end
